package net.zjitc.controller;

import net.zjitc.domain.MessageConstant;
import net.zjitc.domain.Result;
import net.zjitc.domain.ResultPage;
import net.zjitc.domain.User;
import net.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping()
    public Result add(@RequestBody User user){
        try {
            userService.add(user);
        }catch (Exception e){
            return new Result(false,MessageConstant.ADD_USER_FAIL,null);
        }
        return new Result(true,MessageConstant.ADD_USER_SUCCESS,null);
    }
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable("id") Integer id) {
        return userService.delete(id);
    }
    @GetMapping("/{id}")
    public Result findId(@PathVariable("id") Integer id){
        User user;
        try {
            user=userService.findUser(id);
        }catch (Exception e){
            return new Result(false,MessageConstant.QUERY_USER_FAIL,null);
        }
        return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
    }
    @PutMapping
    public Result update(@RequestBody User user){
        try {
            userService.update(user);
        }catch (Exception e){
            return new Result(false,MessageConstant.EDIT_USER_FAIL,null);
        }
        return new Result(true,MessageConstant.EDIT_USER_SUCCESS,null);
    }
    @PostMapping("/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable("currentPage") int currentPage,
                          @PathVariable("pageSize") int pageSize,
                          @RequestBody User user) {
        ResultPage<User> page=null;
        try {
            page=userService.findPage(currentPage,pageSize,user);
        }catch (Exception e){
            return new Result(false, MessageConstant.QUERY_USER_FAIL,null);
        }
        return new Result(true, MessageConstant.QUERY_USER_SUCCESS,page);
    }
}

//{
//        "id": "6",
//        "gender":"男",
//        "username":"q",
//        "password":"098",
//        "email":"w@w.com"
//        }